import React, { Component } from 'react'
import {Card,
    Form,
    Icon,
    Input,
    Button,
    Cascader,
    message
   } from 'antd'
import Linkbutton from '../../components/link-button'
import {reqCategory,reqAddOrUpdate} from '../../api'
import PictureWall from './picturewall.js'
import RichTextEditor from './RichTextEditor.js'

const Item = Form.Item
const { TextArea } = Input;

class Addupdate extends Component {

 constructor(props){
   super(props);
   this.pw = React.createRef()
   this.detail = React.createRef()
 }
   
  state = {
    loading: false,
    options:[],
  };

  


    validatorPrice=(rule, value, callback)=>{

      if(value*1>0){
        callback()
      }else{
        callback('商品价格必须大于0!!!!')
      }

    }
    loadData = async (selectedOptions) => {

      const targetOption = selectedOptions[selectedOptions.length - 1];
      // const targetOption = selectedOptions[0];
      targetOption.loading = true;
 

         const subCategory = await this.getCatgory(targetOption.value)
         targetOption.loading = false;
         if(subCategory && subCategory.length>0){
          const cOptions = subCategory.map(citem=>{
             return {
              value:citem._id,
              label:citem.name,
              isLeaf:false
             }
            
           })
           targetOption.children = cOptions
         }else{
          targetOption.isLeaf = true
         }
         
       
      // load options lazily
 
        this.setState({
          options: [...this.state.options],
        });

    };

    componentDidMount(){
      this.getCatgory('0')
    }

    getCatgory = async (parentId)=>{
          const result = await reqCategory(parentId)
       
          if(result.status === 0){
            const categorys = result.data
            if(parentId === '0'){
                this.initOptions(categorys)
            }else{
              return categorys
            }
          }
    }

    initOptions= async (categorys)=>{
     const options = categorys.map(item =>{
          return {
            value:item._id,
            label:item.name,
            isLeaf:false
          }
      })

      const {isUpdate,product} = this;
      const {pCategoryId} = product
      if(isUpdate && pCategoryId!=='0' ){
        const subCategory = await this.getCatgory(pCategoryId)
        if(subCategory && subCategory.length>0){
        const cOptions = subCategory.map(c=>{
            return {
              value:c._id,
              label:c.name,
              isLeaf:true
            }
          })

          const targetOption = options.find(option => option.value === pCategoryId)

          targetOption.children= cOptions 
  
        }
      }

      this.setState({
        options
      })
  

    }

    componentWillMount(){
      const product = this.props.location.state;
      this.product = product || {}
      this.isUpdate = !!product      //强制转换成字符串
    }


    submit=()=>{
      this.props.form.validateFields(async (err, values) => {
        
        if (!err) {
          console.log('成功提交表单===》 ', values);
          const {name,desc,price,categoryIds} = values

          //   let pCategoryId;
          //   let categoryId;
          // if(categoryIds.length=== 1){
          //   pCategoryId = '0'
          //   categoryId = categoryIds[0]
          // }else{
          //   pCategoryId=categoryIds[0]
          //   categoryId = categoryIds[1]
          // }

          let pCategoryId, categoryId
          if (categoryIds.length===1) {
            pCategoryId = '0'
            categoryId = categoryIds[0]
          } else {
            pCategoryId = categoryIds[0]
            categoryId = categoryIds[1]
          }
        
          const imgs = this.pw.current.getImgs()
          console.log('ref使用===》', imgs)
          // const imgs = this.pw.current.getImgs()
          const detail = this.detail.current.getDetail()
          console.log('tupiandi==>',detail)
          //  const product = {name,desc,price,pCategoryId,categoryId,imgs,detail}
           const product = {name, desc, price, imgs, detail, pCategoryId, categoryId}
          if(this.isUpdate){
            product._id = this.product._id
          }
           const result = await reqAddOrUpdate(product)
           if(result.status===0){
             message.success(`${this.isUpdate?'修改':'添加'}商品成功`)
             this.props.history.goBack()
           }else{
             message.error(`${this.isUpdate?'修改':'添加'}商品失败`);
             
           }
        }
      });
    }

  render() {
    const {options} = this.state
    const {product,isUpdate} = this
    const {categoryId,pCategoryId,detail} = product


    const title=(
      <span>
        <Linkbutton onClick={()=>this.props.history.goBack()}>
          <Icon type="arrow-left" />
          {isUpdate ? '修改商品':'添加商品'}
        </Linkbutton>
      </span>
    )
 

    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span:8 },
    };
    const {getFieldDecorator} = this.props.form
    const categoryIds = [];

    if(isUpdate){
      if(pCategoryId=== '0'){
        categoryIds.push(pCategoryId)
      }else{
        categoryIds.push(pCategoryId)
        categoryIds.push(categoryId)
      }
    }
    return (
      <div>
       <Card title={title}>
         <Form  {...formItemLayout}>
          <Item label="商品名称">
            
            {getFieldDecorator('name',{
             initialValue: product.name,
               rules: [ {required: true, message: '商品名称必须输入'} ]
            })( <Input />)}
            
          </Item>
          <Item label="商品描述">
 
            {getFieldDecorator('desc',{
              initialValue: product.desc,
              rules:[{required:true,message:'商品描述必须输入'}]
            })( <TextArea  autoSize={{ minRows: 2, maxRows: 6 }} placeholder="请输入商品描述" />)}
         
          </Item>
          <Item label="商品价格">

            {getFieldDecorator('price',{
              initialValue:product.price ,
              rules:[{
                required:true,
                message:'商品价格必须输入'
              },{
                validator:this.validatorPrice
              }]
            })( <Input type='number' addonAfter="元"/>)}
            
          </Item>
          <Item label="商品分类">
            
            {getFieldDecorator('categoryIds',{
              initialValue:categoryIds,
              rule:[{required: true, message: '商品分类必须输入'}]
            })(<Cascader
              options={options}
              loadData={this.loadData}
            />)}
          </Item>
          <Item label="商品图片">
            <PictureWall
             ref={this.pw}
             
            imgs={product.imgs} />
          </Item>
          <Item label="商品详情" labelCol={{ span: 2 }} wrapperCol={{ span: 20 }}> 
          <RichTextEditor ref={this.detail}  detail={detail}/>
         
          </Item> 
          <Button type='primary' onClick={this.submit}>提交</Button>
         </Form>
       </Card>
      </div>
    )
  }
}

export default  Form.create()(Addupdate) 
